import 'package:flutter/material.dart';
import 'package:flutter_map/flutter_map.dart';
import 'package:flutter_map_animations/flutter_map_animations.dart';
import 'package:geolocator/geolocator.dart';
import 'package:get/get.dart';
import 'package:flutter_compass/flutter_compass.dart';
import 'dart:async';
import 'dart:math' as math;

import 'package:latlong2/latlong.dart';

class MapTestController extends GetxController
    with GetSingleTickerProviderStateMixin {
  // 响应式罗盘角度 (弧度)
  final RxDouble compassAngle = 0.0.obs;
  // 罗盘事件订阅
  StreamSubscription<double>? _compassSubscription;
  // late MapController mapCtl;
  bool isReady = false;
  final Rx<LatLng> center = const LatLng(39.9, 116.4).obs;
  final markers = ValueNotifier<List<AnimatedMarker>>([]);
  late final AnimatedMapController mapCtl = AnimatedMapController(vsync: this);

  @override
  void onInit() {
    super.onInit();
    _startCompassListening();
    _schedule();
  }

  @override
  void onReady() {
    super.onReady();
    getLocation();
  }

  @override
  void dispose() {
    markers.dispose();
    mapCtl.dispose();
    super.dispose();
  }

  Future<void> getLocation() async {
    print("获取位置1111");
    // 检查并请求权限
    LocationPermission permission = await Geolocator.checkPermission();
    if (permission == LocationPermission.denied) {
      permission = await Geolocator.requestPermission();
      if (permission == LocationPermission.denied) {
        // 权限被拒绝
        return;
      }
    }
    print("获取位置2222");
    // 检查位置服务是否可用
    bool serviceEnabled = await Geolocator.isLocationServiceEnabled();
    if (!serviceEnabled) {
      // 位置服务不可用
      return;
    }
    print("获取位置3333");
    // 获取当前位置
    const LocationSettings locationSettings = LocationSettings(
      accuracy: LocationAccuracy.high,
      distanceFilter: 100,
    );
    print("获取位置444");
    Position position =
        await Geolocator.getCurrentPosition(locationSettings: locationSettings);
    print('当前位置: ${position.latitude}, ${position.longitude}');
    center.value = LatLng(position.latitude, position.longitude);

    // 使用位置数据
  }

// 修改原有调度方法使用通用函数
  void _schedule() {
    Future.delayed(const Duration(seconds: 5), () async {
      mapCtl.animatedFitCamera(
          cameraFit: CameraFit.bounds(
              bounds: LatLngBounds.fromPoints([
        const LatLng(39.9, 116.39),
        const LatLng(39.916527, 116.397128)
      ])));
    });
  }

  // 开始监听罗盘数据
  void _startCompassListening() {
    _compassSubscription = FlutterCompass.events
        ?.map((event) => event.heading ?? 0.0)
        .listen((heading) {
      // 将角度从度转换为弧度，并调整方向
      compassAngle.value = heading * math.pi / 180 * -1;
    });
  }

  @override
  void onClose() {
    // 取消订阅释放资源
    _compassSubscription?.cancel();
    super.onClose();
  }
}
